﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XingLucifer.Devices.Inits
{
    public class TC06 : DevicePing
    {
        public TC06(Action<string> action) : base(XingLucifer.IBase.Enums.DeviceTypes.TC06_Scale, action)
        {
        }

        public override bool Init(string? sourceIP, string? ip, string? dns, int port)
        {
            try
            {
                string str = GetHtml($"http://{sourceIP}/Serial2Net.asp", sourceIP, $"http://{sourceIP}/Serial2Net.asp");
                if (str.Contains("HLK-RM04 Web Configure"))
                {
                    _action?.Invoke("登录成功");
                    Thread.Sleep(1000);
                    str = GetSer2Net($"http://{sourceIP}/ser2net.asp", sourceIP, $"http://{sourceIP}/Serial2Net.asp");
                    if (str.Contains("Copyright (c) Shenzhen Hi-Link Electronic Inc. All Rights Reserved"))
                    {
                        Thread.Sleep(1000);
                        _action?.Invoke("跳转网址设置页面");
                        return !Post(ip);
                    }
                    _action?.Invoke("跳转网址设置页面失败");
                    return false;
                }
                _action?.Invoke("登录失败");
            }
            catch (Exception)
            {
                _action?.Invoke("登录失败");
            }
            return false;
        }

        public override bool Ping(string? ip = null)
        {
            try
            {
                if (ip == "192.168.16.254") { return base.Ping("192.168.16.254"); }
                return !base.Ping(ip);
            }
            catch (Exception)
            {
                return false;
            }
        }

        public override bool Reboot()
        {
            Thread.Sleep(8000);
            return base.Reboot();
        }

        protected string GetHtml(string url, string host, string referer)
        {
            HttpWebRequest request = WebRequest.CreateHttp(url);
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763";
            //request.Host = host;
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.Referer = referer;
            request.Headers.Add("Authorization", "Basic YWRtaW46YWRtaW4=");
            request.Headers.Add("Accept-Encoding", "gzip, deflate");
            request.Headers.Add("Accept-Language", "zh-CN");
            request.Headers.Add("Upgrade-Insecure-Requests", "1");
            request.KeepAlive = true;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            byte[] byte1 = new byte[2048];
            int length = 0;
            using (Stream stream = response.GetResponseStream())
            {
                length = stream.Read(byte1, 0, 2048);
            }
            return System.Text.Encoding.UTF8.GetString(byte1.Take(length).ToArray());
        }

        protected string GetSer2Net(string url, string host, string referer)
        {
            HttpWebRequest request = WebRequest.CreateHttp(url);
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763";
            request.Host = host;
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.Referer = referer;
            request.Headers.Add("Authorization", "Basic YWRtaW46YWRtaW4=");
            request.Headers.Add("Accept-Encoding", "gzip, deflate");
            request.Headers.Add("Accept-Language", "zh-CN");
            request.Headers.Add("Upgrade-Insecure-Requests", "1");
            request.KeepAlive = true;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            byte[] byte1 = new byte[2048];
            int length = 0;
            using (Stream stream = response.GetResponseStream())
            {
                length = stream.Read(byte1, 0, 2048);
            }
            return System.Text.Encoding.UTF8.GetString(byte1.Take(length).ToArray());
        }

        protected bool Post(string ip)
        {
            try
            {
                HttpWebRequest request = WebRequest.CreateHttp("http://192.168.16.254/goform/ser2netconfig2");
                request.Method = "POST";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.KeepAlive = true;
                request.Timeout = 4000;
                request.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763";
                request.Host = "192.168.16.254";
                request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN");
                request.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                request.Headers.Add(HttpRequestHeader.Connection, "keep-alive");
                request.Headers.Add("Authorization", "Basic YWRtaW46YWRtaW4=");
                request.Referer = "http://192.168.16.254/ser2net.asp";
                string data = $"ser2netSave=0&ser2netNetSave=1&netmode=1&wifi_conf=HI-LINK_4AB5%2Cwpa2_aes%2C12345678&dhcpd=1&dhcpd_ip=192.168.16.100%2C192.168.16.200%2C255.255.255.0%2C192.168.16.254&dhcpd_dns=192.168.16.254%2C8.8.8.8&dhcpd_time=86400&dhcpc=0&net_ip={ip}%2C255.255.255.0%2C192.168.11.1&net_dns=192.168.11.1%2C8.8.8.8&default_0_ssid=&default_0_pass=&ser2netUart=9600%2C8%2Cn%2C1&ser2netPacklen=64&ser2netPacktimeout=10&ser2netMode=server&ser2netRemoteport=8080&ser2netRemotepro=tcp&ser2netTimeout=0";
                byte[] bytes = Encoding.ASCII.GetBytes(data);
                request.ContentLength = bytes.Length;
                using (System.IO.Stream stream = request.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
                var resou = request.GetResponse();
                request.Abort();
                return true;
            }
            catch (Exception ex)
            {
                return ex.Message == "An error occurred while sending the request.";
            }
        }
    }
}
